package com.color.admin.common.core.utils.web;


import com.color.admin.common.core.exception.BaseException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.Random;

/**
 * @author HaiQiu
 * @date 2022/2/16
 * 本地文件操作工具类
 */
public class FileUtils {

    public static String upload(MultipartFile multipartFile,String folder){
        if (multipartFile==null){
            throw new BaseException("未发现文件上传");
        }
        if (folder==null){
            throw new BaseException("未选择存储路径");
        }
        File dir = new File(folder);
        if (!dir.exists()){
            dir.mkdir();
        }
        String fileName = generateName(Objects.requireNonNull(multipartFile.getOriginalFilename()));
        File dest = new File(folder + fileName);
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BaseException(multipartFile.getOriginalFilename()+"文件上传失败");
        }
        return fileName;
    }


    public static String generateName(String originalFilename) {
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String date = DateUtils.dateFormat(new Date(), DateUtils.YMDHMS);
        String fileName = date + "_" + getStringRandom(13) + suffix;
        return fileName;
    }

    //生成随机数字和字母,
    public static String getStringRandom(int length) {
        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 删除文件
     * @param fileName 文件绝对路径 + 文件名
     */
    public static void delete(String fileName) {
        File file = new File(fileName);
        try {
            deleteFile(file);
        }catch (Exception e){
            throw new BaseException(String.format("删除文件%s失败",fileName));
        }
    }
    public static void deleteFile(File file) {
        if (file.exists()){
            //是文件直接删除
            if (file.isFile()){
                file.delete();
            }else {
                //递归删除文件
                File[] files = file.listFiles();
                for (File fileChild : files) {
                    deleteFile(fileChild);
                }
            }
            //删除文件夹
            file.delete();
        }
    }
}
